package com.melot.antispam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.hadoop.conf.Configuration;

@SuppressWarnings("serial")
public class AntiSpamServlet extends HttpServlet {
	private Classifier classifier;

	@Override
	public void init() {
		Configuration conf = new Configuration();
		conf.set("fs.defaultFS", Config.hdfsURI);
		conf.set(Classifier.DICTIONARY_PATH_CONF, Config.dictionaryPath);
		conf.set(Classifier.DOCUMENT_FREQUENCY_PATH_CONF,
				Config.documentFrequencyPath);
		conf.set(Classifier.DOCUMENT_PATH_CONF, Config.documentPath);
		conf.set(Classifier.MODEL_PATH_CONF, Config.modelPath);
		conf.set(Classifier.LABEL_INDEX, Config.labelIndexPath);

		try {
			classifier = new Classifier(conf);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String email = readAll(req.getReader());
		long t0 = System.currentTimeMillis();
		String category = classifier.classify(email);
		long t1 = System.currentTimeMillis();

		resp.getWriter().print(
				String.format("{\"category\":\"%s\", \"time\": %d}", category,
						t1 - t0));

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String email = readAll(req.getReader());
		long t0 = System.currentTimeMillis();
		String category = classifier.classify(email);
		long t1 = System.currentTimeMillis();

		resp.getWriter().print(
				String.format("{\"category\":\"%s\", \"time\": %d}", category,
						t1 - t0));

	}

	private String readAll(Reader reader) throws IOException {

		BufferedReader bufReader = new BufferedReader(reader);

		String line;
		StringBuilder sb = new StringBuilder();
		while ((line = bufReader.readLine()) != null) {
			sb.append(line).append(" ");
		}

		return sb.toString();
	}
}
